package cn.demo.client.api;


import cn.demo.common.config.RuoYiConfig;
import cn.demo.common.core.controller.BaseController;
import cn.demo.common.core.domain.MapR;
import cn.demo.common.core.domain.R;
import cn.demo.common.core.domain.entity.SysDictData;
import cn.demo.common.utils.CollectionUtils;
import cn.demo.common.utils.DictUtils;
import cn.demo.common.utils.StringUtils;
import cn.demo.common.utils.file.FileUploadUtils;
import cn.demo.common.utils.file.FileUtils;
import cn.demo.framework.config.ServerConfig;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;


/**
 * 通用接口
 *
 * @author xtjun
 * @date 2023-04-07
 */
@Tag(name = "客户端-通用接口")
@RestController
@RequestMapping("/api/common")
public class CommonApi extends BaseController {

    @Resource
    private ServerConfig serverConfig;

    /**
     * 通用上传请求（单个）
     */
    @Operation(summary = "通用上传请求（单个）")
    @PostMapping("/upload")
    public MapR<Object> uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            MapR<Object> ajax = MapR.ok();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return MapR.fail(e.getMessage());
        }
    }

    @Operation(summary = "获取字典")
    @GetMapping("/dicts")
    public R<List<SysDictData>> dicts(String key) {
        if (StringUtils.isEmpty(key)){
            return R.ok();
        }
        if (key.contains(StringUtils.DELIMITER)){
            List<SysDictData> list = new ArrayList<>();
            for (String s : new HashSet<>(Arrays.asList(key.split(StringUtils.DELIMITER)))) {
                list.addAll(DictUtils.getDictCache(s));
            }
            return R.ok(list);
        }else {
            return R.ok(DictUtils.getDictCache(key));
        }
    }


}
